import React from 'react'
import { connect } from 'react-redux'
import { Select, message, Button, Modal, Form, Input, Popover, Spin } from 'antd';
import baseService from "share/base.service";
import 'styles/financial-account/doc-template.scss';
import SlideFrame from 'components/slide-frame';
import ResizeTable from 'components/resize-table'
import credentialRule from "containers/financial-account/credential-definition/credential-rule";
import credentialService from "containers/financial-account/credential-definition/credential-definition-service";
import { messages, queryCurrencyPrecision } from "share/common";
import menuRoute from "routes/menuRoute";
import { setCredentialDefinition } from 'actions/financial-account';

const FormItem = Form.Item;
const Option = Select.Option;

class credentialDefinition extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      setOfBooks: [],
      setOfBooksId: this.props.company.setOfBooksId,
      page: 0,
      loading: false,
      columns: [
        {
          title: messages('financial-account.key1')/*凭证类别编码*/,
          dataIndex: 'templateCode',
          render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>
        },
        {
          title: messages('financial-account.key2')/*凭证类别名称*/,
          dataIndex: 'templateName',
          render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>
        },
        {
          title: messages('financial-account.key3')/*说明*/,
          dataIndex: 'comment',
          width: '30%',
          render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>
        },
        { title: messages('financial-account.key4')/*来源核算业务类型编码*/, width: '15%', dataIndex: 'functionDefineCode' },
        {
          title: messages('financial-account.key5')/*是否预置*/,
          dataIndex: 'isDefault',
          width: 96,
          render: (value) => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'isEnable',
          width: 80,
          render: (value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operator', render: (value, record) => {
            return (
              <div>
                <a onClick={e => this.handleEdit(e, record)}>{messages('common.edit')/*编辑*/}</a>
                <span className="ant-divider"/>
                <a onClick={e => this.handleGoDetail(e, record)}>{messages('common.detail')/*详情*/}</a>
              </div>)
          }
        }
      ],
      pagination: {
        total: 0
      },
      data: [],
      editRecord: {},
      visible: false,
      expandRecord: {},
      title: '',
      showSlideFrame: false,
      saveLoading: false,
      infoVisible: false,
      infoColumns: [],
      infoData: [],
      options: [],
      fetch: false
    };
  }

  componentWillMount() {
    this.props.dispatch(setCredentialDefinition({}));
    this.getSetOfBook();
    this.getList();
  }

  getList = () => {
    const { setOfBooksId, page } = this.state;
    let temp = {
      setOfBooksId,
      page
    };
    this.setState({ loading: true });
    credentialService.getCredentialList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ loading: false });
    })
  };

  getSetOfBook = () => {
    baseService.getSetOfBooksByTenant().then(res => {
      this.setState({ setOfBooks: res.data })
    }).catch((e) => {
      message.error(e.response.data.message);
    })
  };

  handleChangeBookId = (value) => {
    this.setState({ setOfBooksId: value }, () => {
      this.getList();
    });
  };

  handleEdit = (e, record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key7')/*编辑凭证类别*/,
      editRecord: record
    }, () => {
      this.setState({ showSlideFrame: true });
    })
  };

  handleGoDetail = (e, record) => {
    e.stopPropagation();
    this.props.dispatch(setCredentialDefinition(record));
    this.context.router.push(menuRoute.getRouteItem('credential-detail').url);
  };

  handleNew = () => {
    this.setState({
      title: messages('financial-account.key8')/*新建凭证类别*/,
      editRecord: {}
    }, () => {
      this.setState({ showSlideFrame: true });
    })
  };

  isRefresh = (isRefresh) => {
    this.setState({ showSlideFrame: false });
    isRefresh === true && this.getList();
  };

  renderAllExpandedRow = (expanded, record) => {
    if (expanded) {
      this.props.form.resetFields();
      this.setState({
        expandRecord: record,
        visible: true
      })
    }
  };

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { user, tenant } = this.props;
        const { expandRecord } = this.state;
        let params = {
          businessCode: values.businessCode,
          type: Number(values.type),
          tenantId: tenant.id,
          operatorOid: user.userOID,
          journalTemplateId: expandRecord.id,
          transactionDetailIds: values.transactionDetailIds ? [values.transactionDetailIds] : []
        };
        this.setState({ saveLoading: true });
        credentialService.buildEntry(params).then((res) => {
          this.setState({ saveLoading: false, visible: false }, () => {
            let columns = [];
            if (res.data.length) {
              let temp = res.data[0];
              Object.keys(temp).map(item => {
                columns.push({
                  title: item,
                  dataIndex: item,
                  width: 120,
                  render: value => <Popover content={value}>{value}</Popover>
                });
              });
            }
            this.setState({ infoColumns: columns, infoData: res.data, infoVisible: true });
          });
        }).catch(e => {
          this.setState({ saveLoading: false });
          message.error(e.response.data.message);
        })
      }
    })
  };

  handleOptions = () => {
    const { getFieldsValue } = this.props.form, { tenant } = this.props, { expandRecord } = this.state;
    let temp = getFieldsValue();
    this.setState({ fetch: true });
    credentialService.getTransactionList({
      businessCode: temp.businessCode,
      tenantId: tenant.id,
      journalTemplateId: expandRecord.id,
      type: Number(temp.type)
    }).then(res => {
      this.setState({ fetch: false, options: res.data });
    }).catch(e => {
      this.setState({ fetch: false, options: [] });
      message.error(e.response.data.message);
    })
  };

  render() {
    const {
      setOfBooks, loading, columns, data, pagination, showSlideFrame, title, editRecord, setOfBooksId, visible,
      saveLoading, infoVisible, infoColumns, infoData, options, fetch
    } = this.state;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    return (
      <div className="doc-template">
        <div className='alternation-top'/>
        <div className="audit-opinion-title"> {messages('financial-account.key9')/*帐套：*/}
          <Select onChange={e => this.handleChangeBookId(e)} defaultValue={`${this.props.company.setOfBooksName}`}
                  disabled={!this.props.tenantMode}>
            {
              setOfBooks.map(item => {
                return <Option key={item.id} title={item.setOfBooksName}>{item.setOfBooksName}</Option>
              })
            }
          </Select>
        </div>
        <div className='alternation-middle'/>
        <div style={{ marginTop: '20px' }}>
          <div style={{ marginBottom: '10px' }}>
            <Button type="primary" onClick={this.handleNew} disabled>{messages('common.create')}</Button>
          </div>
          <ResizeTable
            loading={loading}
            columns={columns}
            bordered
            pagination={pagination}
            rowKey={'id'}
            expandedRowRender={() => {
              return <div></div>
            }}
            onExpand={this.renderAllExpandedRow}
            dataSource={data}
          />
        </div>
        <SlideFrame show={showSlideFrame}
                    title={title}
                    params={{
                      showSlideFrame,
                      editRecord,
                      setOfBooksId
                    }}
                    content={credentialRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
        <Modal visible={visible}
               footer={<div>
                 <Button onClick={() => {
                   this.setState({ expandRecord: {}, visible: false })
                 }}>{messages('common.cancel')/*取消*/}</Button>
                 <Button htmlType="submit" onClick={this.handleOk} type='primary'
                         loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
               </div>}
               onCancel={() => {
                 this.setState({ expandRecord: {}, visible: false })
               }}
               title={messages('financial-account.key135')/*分录生成*/}>
          <Form onSubmit={this.handleOk}>
            <FormItem label={messages('common.document.code')/*单号*/} {...formItemLayout}>
              {getFieldDecorator('businessCode', {
                rules: [{
                  required: true, message: messages('common.please.enter')/*请输入*/,
                }],
              })(
                <Input placeholder={messages('common.please.enter')/*请输入*/}/>
              )}
            </FormItem>
            <FormItem label={messages('financial-account.key136')/*单号类型*/} {...formItemLayout}>
              {getFieldDecorator('type', {
                rules: [{
                  required: true, message: messages('common.please.select')/*请选择*/,
                }],
                initialValue: '1002'
              })(
                <Select placeholder={messages('common.please.select')/*请选择*/}>
                  <Option key={'1002'}>报销单</Option>
                  <Option key={'3001'}>借款单</Option>
                  <Option key={'1008'}>还款单</Option>
                </Select>
              )}
            </FormItem>
            {
              getFieldsValue().type && getFieldsValue().businessCode && (
                <FormItem label={'流水号'} {...formItemLayout}>
                  {getFieldDecorator('transactionDetailIds')(
                    <Select
                      placeholder={messages('common.please.select')/*请选择*/}
                      onFocus={this.handleOptions}
                      notFoundContent={fetch ? <Spin size="small"/> : messages('components.key410'/*无匹配结果*/)}
                    >
                      {
                        options.map(item => <Option key={item.id}>
                          {`${item.billCode}-${item.paymentCurrencyCode} ${this.filterMoney(item.paymentAmount, queryCurrencyPrecision(item.paymentCurrencyCode), true)}`}
                        </Option>)
                      }
                    </Select>
                  )}
                </FormItem>
              )
            }
          </Form>
        </Modal>
        <Modal visible={infoVisible}
               footer={null}
               width={900}
               title={messages('financial-account.key160')/*预览信息*/}
               onCancel={() => { this.setState({ infoVisible: false })}}>
          <ResizeTable
            dataSource={infoData}
            bordered
            pagination={false}
            scroll={{ x: true }}
            columns={infoColumns}
          />
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    tenant: state.login.tenant,
    user: state.login.user
  }
}

credentialDefinition.contextTypes = {
  router: React.PropTypes.object
};

const wrappedCredentialDefinition = Form.create()(credentialDefinition);
export default connect(mapStateToProps)(wrappedCredentialDefinition);
